﻿//-----------------------------------------------------------------------
// <copyright file="SettingsManager.cs" company="Nathan Miller">
// Copyright (c) Nathan Miller.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// 
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
//-----------------------------------------------------------------------
namespace TileTool.Base.Settings
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.IO;
    using System.Linq;
    using Newtonsoft.Json;
    using TileTool.Log;
    using TileTool.Settings;

    /// <summary>
    /// Base settings manager.
    /// </summary>
    public class SettingsManager : ISettingsManager
    {
        #region Constants

        /// <summary>
        /// Log group to use.
        /// </summary>
        private const string LogGroup = "SettingsManager";

        #endregion

        #region Fields - Private

        /// <summary>
        /// Dictionary which contains all of our settings objects.
        /// </summary>
        private IDictionary<Type, ISettings> settingsDict = new Dictionary<Type, ISettings>();

        #endregion

        #region Methods - Public

        /// <summary>
        /// Load the settings file at the passed path.
        /// 
        /// This function should not throw any exception in case of error.
        /// 
        /// If there is an error with the settings data, the settings manager should
        /// revert back to default values.
        /// </summary>
        /// <param name="fileName">Path to file to load settings file from.</param>
        public void Load(string fileName)
        {
            LogSystem.LogInfo(LogGroup, "Attempting to load " + fileName);

            IEnumerable<ISettings> loadedSettings = this.LoadSettings(fileName);

            if (loadedSettings == null)
            {
                return;
            }

            // For all loaded settings object, check and see if we need to
            // upgrade them and then add the object to our internal dictionary.
            foreach (ISettings settings in loadedSettings)
            {
                if (settings.Version != settings.CodeVersion)
                {
                    if (!this.UpgradeSettings(settings))
                    {
                        continue;
                    }
                }

                this.settingsDict.Add(settings.GetType(), settings);
            }
        }

        /// <summary>
        /// Save the settings to the passed file name.
        /// </summary>
        /// <param name="fileName">File name to save settings to.</param>
        public void Save(string fileName)
        {
            LogSystem.LogInfo(LogGroup, "Attempting to save to " + fileName);

            IEnumerable<ISettings> allSettings = this.settingsDict.Values;

            this.SaveSettings(fileName, allSettings);
        }

        /// <summary>
        /// Get a settings object of the passed type.
        /// 
        /// If an object of the passed type is not loaded, a default object
        /// should be created and returned. This default object should be stored
        /// and returned for all subsequent calls of Get().
        /// 
        /// The object returned from this function should not be held on to as
        /// calls to Reset() can invalidate the returned object.
        /// </summary>
        /// <typeparam name="T">Type of settings object to get.</typeparam>
        /// <returns>Returns the settings object.</returns>
        public T Get<T>() where T : class, ISettings, new()
        {
            ISettings res = null;

            if (!this.settingsDict.TryGetValue(typeof(T), out res))
            {
                res = new T();
                this.settingsDict.Add(typeof(T), res);
            }

            Debug.Assert(res as T != null, "Must not be null.");

            return res as T;
        }

        /// <summary>
        /// Reset all settings objects.
        /// </summary>
        public void ResetAll()
        {
            IEnumerable<ISettings> allSettings = this.settingsDict.Values;

            foreach (ISettings settings in allSettings)
            {
                settings.Reset();
            }
        }

        /// <summary>
        /// Reset the passed settings type.
        /// </summary>
        /// <typeparam name="T">Settings type to reset.</typeparam>
        public void Reset<T>() where T : class, ISettings, new()
        {
            ISettings obj = this.Get<T>();

            obj.Reset();
        }

        #endregion

        #region Methods - Private

        /// <summary>
        /// Save the passed settings to file.
        /// </summary>
        /// <param name="fileName">File name to save to.</param>
        /// <param name="settings">Settings to save.</param>
        private void SaveSettings(string fileName, IEnumerable<ISettings> settings)
        {
            try
            {
                using (FileStream fileStream = new FileStream(fileName, FileMode.Create))
                {
                    using (StreamWriter streamWriter = new StreamWriter(fileStream))
                    {
                        using (JsonTextWriter jsonWriter = new JsonTextWriter(streamWriter))
                        {
                            JsonSerializerSettings jsonSettings = this.AllocateSettings();
                            JsonSerializer serializer = JsonSerializer.Create(jsonSettings);

                            jsonWriter.Formatting = Formatting.Indented;
                            jsonWriter.Indentation = 4;
                            jsonWriter.IndentChar = ' ';

                            serializer.Serialize(jsonWriter, settings);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                LogSystem.LogError(LogGroup, "Failed to load settings data: " + e.Message);
                LogSystem.LogError(LogGroup, "Exception: " + e.ToString());
            }
        }

        /// <summary>
        /// Load settings from the passed file name.
        /// </summary>
        /// <param name="fileName">File name to load from.</param>
        /// <returns>Returns the loaded settings objects.</returns>
        private IEnumerable<ISettings> LoadSettings(string fileName)
        {
            try
            {
                using (FileStream fileStream = new FileStream(fileName, FileMode.Open))
                {
                    using (StreamReader streamReader = new StreamReader(fileStream))
                    {
                        using (JsonTextReader jsonReader = new JsonTextReader(streamReader))
                        {
                            JsonSerializerSettings jsonSettings = this.AllocateSettings();
                            JsonSerializer serializer = JsonSerializer.Create(jsonSettings);

                            return serializer.Deserialize<IList<ISettings>>(jsonReader);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                LogSystem.LogError(LogGroup, "Failed to load settings data: " + e.Message);
                LogSystem.LogError(LogGroup, "Exception: " + e.ToString());
            }

            return Enumerable.Empty<ISettings>();
        }

        /// <summary>
        /// Allocate a JSON settings object.
        /// </summary>
        /// <returns>Returns the JSON settings object.</returns>
        private JsonSerializerSettings AllocateSettings()
        {
            JsonSerializerSettings jsonSettings = new JsonSerializerSettings();

            jsonSettings.NullValueHandling = NullValueHandling.Ignore;
            jsonSettings.ObjectCreationHandling = ObjectCreationHandling.Auto;
            jsonSettings.TypeNameHandling = TypeNameHandling.Auto;
            jsonSettings.ContractResolver = new SettingsContractResolver();

            return jsonSettings;
        }

        /// <summary>
        /// Upgrade the passed settings object if we can. If we can't upgrade it, return
        /// false which means the settings object should be ignored.
        /// </summary>
        /// <param name="settings">Settings object to upgrade.</param>
        /// <returns>Returns true if the upgrade was a success or false if it failed.</returns>
        private bool UpgradeSettings(ISettings settings)
        {
            if (settings.Version == settings.CodeVersion)
            {
                return true;
            }

            // New settings object and old code, ignore it.
            if (settings.Version > settings.CodeVersion)
            {
                return false;
            }

            try
            {
                while (settings.Version < settings.CodeVersion)
                {
                    settings.Upgrade(settings.Version, settings.Version + 1);

                    int oldVersion = settings.Version;
                    settings.Version = settings.Version + 1;

                    if (settings.Version == oldVersion)
                    {
                        throw new InvalidOperationException("Settings version set did not apply.");
                    }
                }
            }
            catch (Exception e)
            {
                LogSystem.LogError(LogGroup, "Failed to upgrade settings object of type " + settings.GetType().Name);
                LogSystem.LogError(LogGroup, "Error: " + e.ToString());
            }

            return true;
        }

        #endregion
    }
}
